<template>
  <el-row>
    <!--    新建分类模态框 start-->
    <el-dialog
        :before-close="handleClose"
        :visible.sync="dialogVisible"
        title="新建分类"
        width="30%">
      <el-input v-model="input" placeholder="请输入分类名称"></el-input>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="newSort">确 定</el-button>
  </span>
    </el-dialog>
    <!--    新建分类模态框 end-->

    <el-col :span="24">
      <el-button size="medium" type="primary" @click="dialogVisible = true">添加分类</el-button>
    </el-col>
    <el-col>
      <el-table
          :data="tableData"
          height="700"
      >
        <el-table-column
            label="分类名称"
            prop="sort"
        >
        </el-table-column>
        <el-table-column
            label="题目数量"
            prop="number"
        >
        </el-table-column>
        <el-table-column
            label="操作"
        >
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="danger"
                @click="sortDelete(scope.$index)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
</template>

<script>
export default {
  name: "Class",
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      input: ""
    }
  },
  mounted() {
    this.$axios2.post("/sort/list").then((res) => {
      for (let i = 0; i < res.data.sortList.length; i++) {
        this.tableData.push({"sort": res.data.sortList[i].name})
      }
    })
  },
  methods: {
    sortDelete:function(index){
      let name = this.tableData[index].sort
      this.$axios2.post("/delete/sort",{
        'name':name,
      }).then((res) => {
        let code = res.data.code
        if (code === 200){
          this.$message({
            message: '删除分类成功',
            type: 'success'
          });
          this.$router.go(0)
        }else{
          this.$message.error('删除失败，请刷新重试，如无结果请联系管理员！');
        }
      })
    },
    handleClose: function () {
      this.dialogVisible = false
    },
    newSort: function () {
      this.$axios2.post("/new/sort", {
        "name": this.input
      }).then((res) => {
        let code = res.data.code
        this.dialogVisible = false
        if (code == 200) {
          this.$message({
            message: '分类创建成功',
            type: 'success'
          });
          this.$router.go(0)
        } else {
          this.$message.error('创建分类失败！');
        }
      })
    }
  }
}
</script>

<style scoped>

</style>